// API接口请求方法文件
import { axiosInstance, API_ENDPOINTS } from '@/config/api';
import { userStorage } from './storage';

// 短信API
export const smsApi = {
  sendCode: (mobile) => {
    return axiosInstance.post(API_ENDPOINTS.SMS.SEND_CODE, { mobile });
  }
};

// 用户API
export const userApi = {
  loginByMsgCode: (mobile, msgCode, sno = '') => {
    const payload = {
      mobile,
      msgCode,
      sno
    };
    return axiosInstance.post(API_ENDPOINTS.USER.LOGIN_BY_MSG_CODE, payload);
  },

  login: (mobile, pwd) => {
    return axiosInstance.post(API_ENDPOINTS.USER.LOGIN, {
      mobile,
      pwd
    });
  },

  loginByPhone: (phone, code, inviteCode = '', password = '') => {
    return axiosInstance.post(API_ENDPOINTS.USER.LOGIN_BY_PHONE, {
      phone, code, inviteCode, password
    });
  },

  getProfile: () => {
    return axiosInstance.get(API_ENDPOINTS.USER.PROFILE);
  },

  getUserInfo: () => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.GET_INFO, { token });
  },

  changeUserInfo: (payload = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.CHANGE_INFO, {
      token,
      ...payload
    });
  },

  changeMobile: ({ mobile, pwd }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.CHANGE_MOBILE, {
      token,
      mobile,
      pwd
    });
  },

  logout: () => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.LOGOUT, { token });
  },

  register: ({ mobile, pwd = '123456', sno = '', msgCode }) => {
    const data = { mobile, pwd };
    if (sno && sno.trim()) data.sno = sno.trim();
    if (msgCode) data.msgCode = msgCode;
    return axiosInstance.post(API_ENDPOINTS.USER.REGISTER, data);
  },

  getUserAccountLog: (page = 1, size = 10) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.GET_USER_ACCOUNT_LOG, { token, page, size });
  },

  getWithdrawLog: (page = 1, size = 10) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.GET_WITHDRAW_LOG, { token, page, size });
  },

  bindAlipay: ({ real_name, alipay }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.BIND_ALIPAY, { token, real_name, alipay });
  },

  myTeamList: (page = 1, size = 10, type) => {
    const token = userStorage.getToken();
    const payload = { token, page, size };
    if (typeof type !== 'undefined') payload.type = type;
    return axiosInstance.post(API_ENDPOINTS.USER.MY_TEAM_LIST, payload);
  },

  realNameTwo: ({ real_name, idcard, mobile, msgCode }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.REAL_NAME_TWO, { 
      token, 
      real_name, 
      idcard, 
      mobile, 
      msgCode 
    });
  },

  withdraw: ({ money, type = 0 }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.WITHDRAW, { token, money, type });
  },

  recharge: ({ money }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.RECHARGE, { token, money });
  },

  rechargePay: ({ recharge_id, type, pay_type }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.USER.RECHARGE_PAY, { token, recharge_id, type, pay_type });
  },

  getWxLoginCode: (callback_url = 'https://site.shixiaoquan.com/pages/login/wxlogin') => {
    return axiosInstance.post(API_ENDPOINTS.WECHAT.GET_WX_LOGIN_CODE, { callback_url });
  },

  wxLogin: (code, sno = '') => {
    const payload = { 
      code,
      sno
    };
    return axiosInstance.post(API_ENDPOINTS.WECHAT.WX_LOGIN, payload);
  },

  bindMobile: (token, mobile, msgCode, sno = '') => {
    const payload = { 
      token, 
      mobile, 
      msgCode,
      sno
    };
    
    return axiosInstance.post(API_ENDPOINTS.USER.BIND_MOBILE, payload);
  }
};

// 首页相关API
export const indexApi = {
  getBannerList: () => {
    return axiosInstance.get(API_ENDPOINTS.INDEX.GET_BANNER_LIST);
  },

  getMenuList: () => {
    return axiosInstance.get(API_ENDPOINTS.INDEX.GET_MENU_LIST);
  },

  getNoticeList: (type, page = 1, size = 10) => {
    const token = userStorage.getToken();
    const payload = { token, page, size };
    if (typeof type !== 'undefined') payload.type = type;
    return axiosInstance.post(API_ENDPOINTS.INDEX.GET_NOTICE_LIST, payload);
  },

  getNoticeInfo: (payload) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.INDEX.GET_NOTICE_INFO, payload);
  },

  getUserNoReadMsgList: (payload) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.INDEX.GET_USER_NO_READ_MSG_LIST, payload);
  },

  getUserNoReadMsgCount: (token) => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.GET_USER_NO_READ_MSG_COUNT, { token });
  },

  setNoticeRead: (payload) => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.SET_NOTICE_READ, payload);
  },

  setAllNoticeRead: (token) => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.SET_ALL_NOTICE_READ, { token });
  },

  // 文章相关API
  getAllArticleType: () => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.ALL_ARTICLE_TYPE);
  },

  findArticles: ({ type, page = 1, size = 10 }) => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.FIND_ARTICLES, { type, page, size });
  },

  findArticleById: (article_id) => {
    return axiosInstance.post(API_ENDPOINTS.INDEX.FIND_ARTICLE_BY_ID, { article_id });
  },

  uploadFile: (filePath, name = 'file') => {
    const token = userStorage.getToken();
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: API_ENDPOINTS.INDEX.UPLOAD_FILE,
        filePath,
        name,
        header: token ? { token } : {},
        success: (res) => {
          try {
            const raw = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
            const savePath = raw?.data?.save_path || raw?.save_path || raw?.data?.url || raw?.url || raw?.data?.path || raw?.path || raw?.data;
            if (typeof savePath === 'string' && savePath) {
              resolve(savePath);
            } else {
              reject(new Error(raw?.msg || '上传失败'));
            }
          } catch (e) {
            reject(new Error('上传响应解析失败'));
          }
        },
        fail: (err) => {
          reject(new Error(err?.errMsg || '上传失败'));
        }
      });
    });
  }
};

// 商品相关API
export const goodsApi = {
  getGoodsClass: () => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_GOODS_CLASS, { token });
  },

  getGoodsList: ({ class_id = 0, type, kwd = '', page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    const payload = { token, class_id, page, size };
    if (typeof type !== 'undefined') payload.type = type;
    if (kwd && kwd.trim()) payload.kwd = kwd.trim();
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_GOODS_LIST, payload);
  },

  getGoodsInfo: (id) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_GOODS_INFO, { token, id });
  },

  getGoodsByClass: (class_id) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_GOODS_BY_CLASS, { token, class_id });
  },

  createOrder: ({ carmine_id, accounts = [], goodsList, remark = '', type = 1 }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CREATE_ORDER, {
      token,
      carmine_id,
      accounts: Array.isArray(accounts) ? JSON.stringify(accounts) : JSON.stringify([]),
      goodsList: Array.isArray(goodsList) ? JSON.stringify(goodsList) : JSON.stringify([goodsList]),
      remark,
      type
    });
  },

  addGoods: ({ goods_id, carmines }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.ADD_GOODS, {
      token,
      goods_id,
      carmines: JSON.stringify(carmines)
    });
  },

  userOrderList: ({ status = 0, type = 0, page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.USER_ORDER_LIST, {
      token,
      status,
      type,
      page,
      size
    });
  },

  userOrderInfo: (id) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.USER_ORDER_INFO, {
      token,
      id
    });
  },

  userOrderPay: ({ token, id, type }) => {
    return axiosInstance.post(API_ENDPOINTS.GOODS.USER_ORDER_PAY, {
      token,
      id,
      type
    });
  },

  findGrabOrderByUser: ({ bus_status, type, page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.FIND_GRAB_ORDER_BY_USER, {
      token,
      bus_status,
      type,
      page,
      size
    });
  },



  getClassByType: (type) => {
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_CLASS_BY_TYPE, { type });
  },

  getGoodsSpecs: ({ class_id, type = 1 }) => {
    return axiosInstance.post(API_ENDPOINTS.GOODS.GET_GOODS_SPECS, {
      class_id,
      type
    });
  },

  getGoodsTemps: () => {
    return axiosInstance.get(API_ENDPOINTS.GOODS.GET_GOODS_TEMPS);
  },

  findAllCarmineByUser: ({ status = 0, page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.FIND_ALL_CARMINE_BY_USER, {
      token,
      status,
      page,
      size
    });
  },

  grabOrder: ({ channel_ids = [], specs_ids = [], addresss = [], temp_id = [] }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.GRAB_ORDER, {
      token,
      channel_ids: JSON.stringify(channel_ids),
      specs_ids: JSON.stringify(specs_ids),
      addresss: JSON.stringify(addresss),
      temp_id: JSON.stringify(temp_id)
    });
  },

  confirmGrabOrder: (order_ids = []) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CONFIRM_GRAB_ORDER, {
      token,
      order_ids: JSON.stringify(order_ids)
    });
  },

  reservationGoods: ({ specs_ids, channel_ids = [], addresss = [], bus_money, count = 1 }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.RESERVATION_GOODS, {
      token,
      specs_ids,
      channel_ids: JSON.stringify(channel_ids),
      addresss: JSON.stringify(addresss),
      bus_money,
      count
    });
  },

  channelList: () => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CHANNEL_LIST, {
      token
    });
  },

  changeOrdersType: ({ order_id, images = [], bus_status, channel_id }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CHANGE_ORDERS_TYPE, {
      token,
      order_id,
      images: JSON.stringify(images),
      bus_status,
      channel_id
    });
  },

  abandonOrder: ({ order_id }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.ABANDON_ORDER, {
      token,
      order_id
    });
  },

  orderCancel: ({ order_id }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.ORDER_CANCEL, {
      token,
      order_id
    });
  },

  confirmOrder: ({ order_id }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CONFIRM_ORDER, {
      token,
      order_id
    });
  },

  shelfCarmins: ({ carmine_id, type }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.SHELF_CARMINS, {
      token,
      carmine_id,
      type
    });
  },

  changeCarminePrice: ({ carmine_id, price }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.GOODS.CHANGE_CARMINE_PRICE, {
      token,
      carmine_id,
      price
    });
  }
};

// 订单相关API
export const orderApi = {
  getCarmines: (order_id) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.GET_CARMINES, {
      token,
      order_id
    });
  },

  objectionOrder: ({ order_id, content, image }) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.OBJECTION_ORDER, {
      token,
      order_id,
      content,
      image
    });
  },

  getTradeNoticeList: ({ type = 1, page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.GET_TRADE_NOTICE_LIST, {
      token,
      type,
      page,
      size
    });
  },

  getBuyOrderNotice: ({ page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.GET_BUY_ORDER_NOTICE, {
      token,
      page,
      size
    });
  },

  getSellOrderNotice: ({ page = 1, size = 10 } = {}) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.GET_SELL_ORDER_NOTICE, {
      token,
      page,
      size
    });
  },

  markTradeNoticeRead: (notice_id) => {
    const token = userStorage.getToken();
    return axiosInstance.post(API_ENDPOINTS.ORDER.MARK_TRADE_NOTICE_READ, {
      token,
      notice_id
    });
  }
};

// 导出默认API对象
const api = {
  ...smsApi,
  ...userApi,
  ...indexApi,
  ...goodsApi,
  ...orderApi
};

export default api;
export { axiosInstance };